<template>
	<view>
		<view v-if="avatarUrl!==''" class="content" @click="handleAvatar">
			<view>头像</view>
			<button class="avatar-btn" open-type="chooseAvatar" @chooseavatar="chooseavatar">
				<image class="avatar" :src="avatarUrl"></image>
			</button>
		</view>

		<view v-if="nickName!==''" class="content" @click="handleAvatar">
			<view>昵称</view>
			<input style="text-align: right;" :value="nickName" type="nickname" placeholder="请输入昵称" @blur="blur" />
		</view>

		<view class="notice">昵称限2～24个字符,一个汉字为2个字符</view>

		<button class="submit" @click="submit">提 交</button>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'

	const avatarUrl = ref("")
	const nickName = ref("")
	const userInfo = ref()

	onShow(() => {
		try {
			const value = uni.getStorageSync("userInfo");
			if (value) {
				userInfo.value = value
				avatarUrl.value = value.avatarUrl
				nickName.value = value.nickName
			}
		} catch (e) {
			console.log(e)
		}
	})

	async function chooseavatar(e) {
		// console.log('chooseavatar', e)
		const resullt = await uniCloud.uploadFile({
			filePath: e.detail.avatarUrl,
			cloudPath: '/avatar/' + new Date().getTime() + e.detail.avatarUrl.match(/\.[^.]+?$/)[0],
		}).then((res) => {
			// console.log('res',res)
			uniCloud.getTempFileURL({
				fileList: [res.fileID]
			}).then(urlRes => {
				// console.log('urlRes',urlRes)
				avatarUrl.value = urlRes.fileList[0].tempFileURL
			});
		}).catch((err) => {
			console.log('err', err)
		})
	}

	function blur(e) {
		// console.log('blur', e)
		nickName.value = e.detail.value
	}

	function submit() {
		// 节流
		uni.$uv.throttle(() => {
			request()
		}, 1000)
	}

	async function request() {
		if (nickName.value.length > 12) {
			uni.showToast({
				title: '昵称限2～24个字符',
				icon: 'none'
			});
			return
		}
		const db = uniCloud.database();
		const usersCollection = db.collection('user');

		try {
			// 查询用户是否已存在
			const a = await usersCollection.where({
				_id: userInfo.value.userId
			}).get();
			// console.log('a', a)
			// 客户端API查询有result
			let userList = a.result.data

			const currentTime = Date.now();
			if (userList && userList.length > 0) {
				let userData = {
					avatarUrl: avatarUrl.value,
					nickName: nickName.value,
					lastLoginTime: currentTime
				};
				// 用户已存在，更新信息
				uni.showLoading({
					mask: true
				});
				const {
					result
				} = await usersCollection
					.doc(userList[0]._id)
					.update(userData);
				// console.log('result', result)
				uni.hideLoading();
				if (result.errCode === 0) {
					uni.showToast({
						title: '更新成功',
						icon: 'none'
					});
					uni.setStorageSync('userInfo', {
						...userInfo.value,
						...userData
					});
				} else {
					uni.showToast({
						title: result.errMsg,
						icon: 'none'
					});
				}
			} else {
				console.log('用户不存在')
			}
		} catch {
			console.log('服务器异常')
		}
	}
</script>

<style>
	@import 'profile.css'
</style>